home *** CD-ROM | disk | FTP | other *** search
- Path: isis.interpac.net!stacys
- From: stacys@isis.interpac.net (Stacy Sherman)
- Newsgroups: comp.lang.c
- Subject: Newbie question: Is this code OK?
- Date: 17 Jan 1996 07:41:58 GMT
- Organization: Inter-Pacific Networks
- Message-ID: <4di986$fk1@pegasus.interpac.net>
- NNTP-Posting-Host: isis.interpac.net
- X-Newsreader: TIN [version 1.2 PL2]
-
- I'm learning C and would like to know your opinions on my answer to an
- exercise. I was supposed to write a function that counts the number of
- words in a string (array of char in this case, with the length specified
- in a variable). Of course the biggest problem is stripping out all the
- extraneous white space that may be there. In this exercise, whitespace
- separating words was either a space, tab or newline character.
-
- The code I wrote worked on every case I gave it but I want to know if it
- was well written. Specifically:
-
- I know it's usually not a good idea to increment a loop counter within a
- loop, but I have 2 nested loops using the same counter. Was this a bad
- thing to do?
-
- I have an if statement and a for loop that test for the same things. Is
- it possible to somehow combine these into one statement? I couldn't
- think of a way to do it.
-
- Do I need the empty {} after a for loop that has no body? I assumed if I
- didn't, the loop would execute the next statement after it.
-
- Any other comments? Here's the code:
-
- int words (char string[80], int length)
- {
- int i, num_words = 0;
-
- for (i=0; i<length; i++)
- { /* if char isn't whitespace */
- if ((string[i]!='\n') &&
- (string[i]!='\t') &&
- (string[i]!=' '))
- {
- num_words++; /* Increment num_words */
- for (; i<length, ((string[i]!='\n') &&
- (string[i]!='\t') &&
- (string[i]!=' ')); i++)
- /* and skip past any other */
- /* chars that may be there */
- { } /* loop does all work, nothing inside body */
- }
- }
- return (num_words);
- }
-